from QNetworkPipe import QNetworkPipe
from Cube.network.QClient import QClient
from Cube.network import QDefaultPort
# task
from direct.task import Task
# Cmd
from Cube.command.QCommand import QCmdIdle
from EventDefine import event_CMDPIPE_SYNCFAIL, event_CMDPIPE_SERVERLEAVE

class QClientModePipe(QNetworkPipe):
    def __init__(self, CmdDispatchPeriods = 0.1):
        QNetworkPipe.__init__(self, CmdDispatchPeriods)
        self._Client = QClient()
        self._Client.ProcessDataHandleSet(self.CmdBufferReceiveHandle)
        self._Client.NewConnectionHandleSet(self.ServerLinkIDSetHandle)
        self._NetworkObj = self._Client

        self._sn = 0  # test

    def NetworkSetup(self, ip_address='localhost', port_address=QDefaultPort):
        bSuccess = self._Client.Setup(ip_address, port_address)
        return bSuccess

    # override it
    def CommandDispatchTask(self, task):
        self._sn += 1
        if self.CmdDispatchEnable:
            # sync success - cmd execution
            ret = QNetworkPipe.CommandDispatchTask(self, task)
            cmdBuffer = self.CmdQueue.SendOutCmdBufferGet()
            if not cmdBuffer:
                self.NullCmdPush(cmdBuffer)
            self._Client.DataObjSend(cmdBuffer)
            self.CmdDispatchEnable = False
        else:
            # sync fail - check connection state
            deadConnectionIndexList = self._Client.DeadConnectionIndexGet()
            messenger.send(event_CMDPIPE_SYNCFAIL)  # do count down
            print "event_CMDPIPE_SYNCFAIL", self._sn, deadConnectionIndexList
            if deadConnectionIndexList:
               self.DisconnectionHandle(deadConnectionIndexList)
            ret = Task.again
        return ret

    def ExecutionComandUpdate(self):
        pass

    def CmdBufferReceiveHandle(self, dataObject):
        #print dataObject
        self.CmdQueue.ExeCmdQueueMerge(dataObject)
        self.CmdDispatchEnable = True

    def ServerLinkIDSetHandle(self, LinkID):
        self.ServerLinkID = LinkID

    def DisconnectionHandle(self, deadConnectionIndexList):
        self._Client.ConnectionRemove(deadConnectionIndexList)
        messenger.send(event_CMDPIPE_SERVERLEAVE)

    def destroy(self):
        QNetworkPipe.destroy(self)
        self._Client.Close()

    # only use in testing
    def TestPatternSend(self):
        QCmdIdle().InputSend(1,["running"])
